package StudyCode.summary.csv;

import java.util.Arrays;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class StringArrayToCSVLine {

	public static void main(String[] args) {
		String[] strings = new String[3];
		strings[0] = "www";
		strings[1] = "tah1986";
		strings[2] = "com";
		System.out.println("String 数组:" + Arrays.toString(strings));
		System.out.println("转为CSV行");
		System.out.println(toCSVLine(strings));
	}

	public static String toCSVLine(String[] strArray) {
		if (strArray == null) {
			return "";
		}
		StringBuffer cvsLine = new StringBuffer();
		for (int idx = 0; idx < strArray.length; idx++) {
			String item = addQuote(strArray[idx]);
			cvsLine.append(item);
			if (strArray.length - 1 != idx) {
				cvsLine.append(',');
			}
		}
		return cvsLine.toString();
	}

	private static String addQuote(String item) {
		if (item == null || item.length() == 0) {
			return "\"\"";
		}
		StringBuffer sb = new StringBuffer();
		sb.append('"');
		for (int idx = 0; idx < item.length(); idx++) {
			char ch = item.charAt(idx);
			if ('"' == ch) {
				sb.append("\"\"");
			} else {
				sb.append(ch);
			}
		}
		sb.append('"');
		return sb.toString();
	}
}
